package m3;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * @author Chenwx
 * @date 2021/5/14 10:14
 */
public class Consumer {
    public static void main(String[] args) throws MQClientException {
        // 创建消费者对象
        DefaultMQPushConsumer c = new DefaultMQPushConsumer("group3");
        // 设置 name server
        c.setNamesrvAddr("192.168.64.141:9876");
        // 从 Topic1 订阅 TagA、TagB、TagC 标签的消息
        c.subscribe("Topic3", "*"); // 接收所有标签的消息
        // c.subscribe("Topic1", "TagA || TagB || TagC"); // 接收指定标签的消息
        // 设置处理消息的监听器
        // Concurrently 监听器可以启动多个线程，并行处理多条消息
        c.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                for (MessageExt ext : msgs) {
                    byte[] body = ext.getBody();
                    String s = new String(body);
                    System.out.println("收到： "+s);
                }
                //向 rocketmq 返回消息处理状态
                // return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                // 消息处理失败，可以抛异常，或者也可以返回“重新消费”状态
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        });

        // 启动
        c.start();
    }
}
